//
//  VideoDetailController.m
//  Tang
//
//  Created by lanou on 15/12/4.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "VideoDetailController.h"
#import "VideoDetailCell.h"
#import "AppDelegate.h"
#import "VideoPlayerController.h"

#define  KUrl @"http://app.meilihuli.com/api/course/categoryList/page/%ld/count/20/category_id/%ld"


@interface VideoDetailController ()
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, assign) NSInteger moreNum;
@end
static NSString *cellIndentifer = @"cell";
@implementation VideoDetailController


- (NSMutableArray *)modelArray
{
    if (!_modelArray)
    {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.moreNum = 1;
    self.tableView.separatorStyle = NO;
    [self.tableView registerClass:[VideoDetailCell class] forCellReuseIdentifier:cellIndentifer];
    self.navigationItem.title = self.titleName;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
    {
        
        [self requestWithUrl:[NSString stringWithFormat:KUrl,1,_coure_id]];
        [self.tableView.mj_header endRefreshing];
        
    }];
    [self.tableView.mj_header beginRefreshing];
    
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^
    {
        self.moreNum = self.moreNum + 1;
        [self requestWithUrl:[NSString stringWithFormat:KUrl,_moreNum,_coure_id]];
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
    
}

- (void)requestWithUrl:(NSString *)url
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if (data == nil)
          {
              NSLog(@"加载失败%@",error);
              UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
              UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  [self dismissViewControllerAnimated:YES completion:nil];
              }];
              [alertView addAction:OKaction];
              [self presentViewController:alertView animated:YES completion:nil];
              return ;
          }
//          else
//          {
          NSDictionary *firDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          if (_moreNum == 1)
          {
              [self.modelArray removeAllObjects];
          }
          for (NSDictionary *secDic in firDic[@"data"])
          {
              VideoDetailModel * model = [[VideoDetailModel alloc] init];
              [model setValuesForKeysWithDictionary:secDic];
              [self.modelArray addObject:model];
          }
          dispatch_async(dispatch_get_main_queue(), ^{
              [self.tableView reloadData];
              [[NetworkState shareInstance] finshYYToVc:self];
          });
          
//          }
          
          
        
    }] resume];

}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
     if(_modelArray.count !=0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifer forIndexPath:indexPath];
    
    VideoDetailModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    [cell.like removeTarget:self action:@selector(likeButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell.like addTarget:self action:@selector(likeButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.like.tag = 2000+indexPath.row;
    
    return cell;
}

- (void)likeButton:(DIYButton *)btn
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
        btn.selected = !btn.selected;
        VideoDetailModel *model = self.modelArray[btn.tag - 2000];
        
        
        if (btn.selected)
        {
            
            [[CoreDataMan shareIntance] addPlay:model.course_video imagUrl:model.course_cover title:model.course_title width:[model.course_cover_width integerValue] height:[model.course_cover_height integerValue]];
        }
        else
        {
            [[CoreDataMan shareIntance] deletePlayWithId:model.course_video];
        }
    }
    else
    {
        [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消"uiViewController:self];
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        VideoDetailModel *model = self.modelArray[indexPath.row];
    return [VideoDetailCell cellHeightFromModel:model];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoDetailModel *model = self.modelArray[indexPath.row];
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.isRotation = YES;
    
    VideoPlayerController *videoPlayer = [[VideoPlayerController alloc]init];
    videoPlayer.url = model.course_video;
    videoPlayer.name = model.course_title;
    [self presentViewController:videoPlayer animated:NO completion:nil];
}
@end
